﻿using System;
using System.Collections.Generic;
using System.Linq;
using Aquarinum.Base.Infrastructure.Cache;
using Aquarinum.Base.Infrastructure.WebSocket.Interface;
using Aquarinum.WebSocekt.Core.Dtos;

namespace Aquarinum.Base.Infrastructure.WebSocket.InterfaceImp
{
    public class DefaultMessageCacheHandler : IMessageCacheHandler
    {
        // ReSharper disable once InconsistentNaming
        private const string MESSAGE_REDISKEY_PIX = "WEBSOCKET_MESSAGE";
        private readonly ICachingProvider<WebsocketMessageDto> _messageCachingProvider;

        public bool CheckMessageHasExpire()
        {
            return true;
        }

        //todo 构造
        //public DefaultMessageCacheHandler(ICachingProvider<WebsocketMessageDto> messageCachingProvider)
        //{
        //    _messageCachingProvider = messageCachingProvider;
        //}

        //public DefaultMessageCacheHandler()
        //{
        //    //_messageCachingProvider = messageCachingProvider;
        //}

        public void SaveMessage(WebsocketMessageDto socketMessage, long expireSecond)
        {
            _messageCachingProvider.Add($"{MESSAGE_REDISKEY_PIX}_{socketMessage.To}_{socketMessage.Id}", socketMessage,
                TimeSpan.FromSeconds(expireSecond));
        }

        public IList<WebsocketMessageDto> GetMessage()
        {
            return _messageCachingProvider.GetByPrefix($"{MESSAGE_REDISKEY_PIX}").Values.Where(x => x.HasValue)
                .Select(x => x.Value).ToList();
        }

        public IList<WebsocketMessageDto> GetMessageByToClient(string toCliet)
        {
            return _messageCachingProvider.GetByPrefix($"{MESSAGE_REDISKEY_PIX}_{toCliet}").Values
                .Where(x => x.HasValue)
                .Select(x => x.Value).ToList();
        }
    }
}